package com.freesun.shop.service.imp;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.freesun.shop.entity.*;
import com.freesun.shop.mapper.*;
import com.freesun.shop.service.TransportService;
import com.freesun.shop.vo.ShopCartItem;
import org.apache.dubbo.config.annotation.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zf
 * @since 2019-11-13
 */
@Service(timeout = 7000)
public class TransportServiceImpl extends ServiceImpl<TransportMapper, Transport> implements TransportService {
    private static Logger logger = LoggerFactory.getLogger(TransportServiceImpl.class);
    @Autowired
    private TransfeeMapper transfeeMapper ;
    @Autowired
    private TranscityMapper transcityMapper;
    @Autowired
    private TransfeeFreeMapper transfeeFreeMapper;
    @Autowired
    private TranscityFreeMapper transcityFreeMapper;
    @Autowired
    private AreaMapper areaMapper;
    @Override
    public IPage<Transport> findByPage(Transport transport, Page<Transport> page) {
        logger.info("分页查询运费模板,当前页:{},每页大小:{}", page.getCurrent(), page.getSize());
        IPage<Transport> iPage = this.baseMapper.selectPage(page, new LambdaQueryWrapper<Transport>()
                .like(StringUtils.hasText(transport.getTransName()), Transport::getTransName, transport.getTransName()));
        return iPage;
    }

    @Override
    @Transactional
    public boolean save(Transport entity) {
        Assert.notNull(entity, "运费模板不能为空。");
        Assert.notNull(entity.getTransName(), "运费模板名称不能为空。");
        logger.info("新增一个运费模板");
        boolean falg = super.save(entity);
        saveFeeTransport(entity);
        return falg;
    }

    private void saveFeeTransport(Transport entity) {
        //处理收费
        handlerTransFees(entity);
        //处理免费
        handlerTransFeesFree(entity);
    }

    private void handlerTransFeesFree(Transport entity) {
        List<TransfeeFree> transfeeFrees = entity.getTransfeeFrees(); //达到改规则可以免费
        if (transfeeFrees.size() > 0) {  //有规则
            for (TransfeeFree transfeeFree : transfeeFrees) {
                if (transfeeFree.getFreeCityList() == null || transfeeFree.getFreeCityList().isEmpty()) {
                    continue;
                }
                transfeeFree.setTransportId(entity.getTransportId());
                transfeeFreeMapper.insert(transfeeFree);
                List<Area> freeCityList = transfeeFree.getFreeCityList();
                for (Area area : freeCityList) {
                    TranscityFree transcityFree = new TranscityFree();
                    transcityFree.setTransfeeFreeId(transfeeFree.getTransfeeFreeId());
                    transcityFree.setFreeCityId(area.getAreaId());
                    transcityFreeMapper.insert(transcityFree);
                }
            }
        }
    }

    private void handlerTransFees(Transport entity) {
        List<Transfee> transfees = entity.getTransfees(); //收费的标准
        Transfee transfeeAllCity = transfees.get(0);
        transfeeAllCity.setTransportId(entity.getTransportId());
        transfeeMapper.insert(transfeeAllCity);
        if (transfees.size() > 1)  { //不仅有全国统一标准，还有特殊标准
            for (int i = 1; i < transfees.size(); i++) {
                Transfee transfee = transfees.get(i);
                transfee.setTransportId(entity.getTransportId());
                transfeeMapper.insert(transfee);
                List<Area> cityList = transfee.getCityList();
                Assert.notEmpty(cityList,"特殊标准的城市不能为Null");
                cityList.forEach(area -> {
                    Transcity transcity = new Transcity();
                    transcity.setCityId(area.getAreaId());
                    transcity.setTransfeeId(transfee.getTransfeeId());
                    transcityMapper.insert(transcity);
                });
            }
        }
    }

    @Override
    public Transport getById(Serializable id) {
        logger.info("查询的ID：{}",id);
        Transport transport = super.getById(id);
        transport.setTransfees(getTransfees(transport));
        transport.setTransfeeFrees(getTransfeeFrees(transport));
        return transport;
    }

    private List<TransfeeFree> getTransfeeFrees(Transport transport) {
        List<TransfeeFree> transfeeFrees = transfeeFreeMapper.selectList(new LambdaQueryWrapper<TransfeeFree>()
                .eq(TransfeeFree::getTransportId, transport.getTransportId()));
        if (transfeeFrees != null && transfeeFrees.size() > 0) {
            for (TransfeeFree transfeeFree : transfeeFrees) {
                transfeeFree.setFreeCityList(getFreeCityList(transfeeFree.getTransfeeFreeId()));
            }
        }
        return transfeeFrees;
    }

    private List<Area> getFreeCityList(Long transfeeFreeId) {
        List<Object> areaIds = transcityFreeMapper.selectObjs(new LambdaQueryWrapper<TranscityFree>()
                .select(TranscityFree::getFreeCityId)
                .eq(TranscityFree::getTransfeeFreeId, transfeeFreeId));
        if (areaIds != null && areaIds.size() > 0) {
            List<Area> areaList = areaMapper.selectList(new LambdaQueryWrapper<Area>()
                    .in(Area::getAreaId, areaIds));
            return areaList;
        }else {
            throw new RuntimeException("免费的城市标准里面城市列表不能为Null");
        }
    }

    private List<Transfee> getTransfees(Transport transport) {
        List<Transfee> transfees = transfeeMapper.selectList(new LambdaQueryWrapper<Transfee>().eq(Transfee::getTransportId, transport.getTransportId()));
        if (transport.getIsFreeFee() == 1 ) {
            return transfees;
        }
        if (transfees.size() > 1) {
            for (int i = 1; i < transfees.size(); i++) {
                Transfee transfee = transfees.get(i);
                transfee.setCityList(getFeeCityList(transfee.getTransfeeId()));
            }
        }
        return transfees;
    }

    private List<Area> getFeeCityList(Long transfeeId) {
        List<Object> areaIds = transcityMapper.selectObjs(new LambdaQueryWrapper<Transcity>()
                .select(Transcity::getCityId)
                .eq(Transcity::getTransfeeId, transfeeId));

        if (areaIds != null && areaIds.size() > 0) {
            List<Area> areaList = areaMapper.selectList(new LambdaQueryWrapper<Area>()
                    .in(Area::getAreaId, areaIds));
            return areaList;
        }else {
            throw new RuntimeException("收费的城市标准里面城市列表不能为Null");
        }
    }

    /**
     * 批量删除
     */
    @Override
    public boolean removeByIds(Collection<? extends Serializable> idList) {
        Assert.notEmpty(idList,"批量删除时ID集合不能为Null");
        logger.info("批量删除的ID为:{}",idList);
        for (Serializable id : idList) {
            deleteRealtion(id);
        }
        return super.removeByIds(idList);
    }

    private void deleteRealtion(Serializable id) {
        Transport transport = getById(id);
        if (null == transport) {
            throw new RuntimeException("要删除的数据不存在");
        }
        if (transport.getTransfeeFrees().size() > 0) {
            List<TransfeeFree> transfeeFrees = transport.getTransfeeFrees();
            for (TransfeeFree transfeeFree : transfeeFrees) {
                if (transfeeFree.getFreeCityList().size() > 0) {
                    transcityFreeMapper.delete(new LambdaQueryWrapper<TranscityFree>()
                    .eq(TranscityFree::getTransfeeFreeId,transfeeFree.getTransfeeFreeId()));
                }
            }
            transfeeFreeMapper.delete(new LambdaQueryWrapper<TransfeeFree>()
                    .eq(TransfeeFree::getTransportId,id));
        }
        if (transport.getTransfees().size() > 0) {
            List<Transfee> transfees = transport.getTransfees();
            for (Transfee transfee : transfees) {
                transcityMapper.delete(new LambdaQueryWrapper<Transcity>()
                .eq(Transcity::getTransfeeId,transfee.getTransfeeId()));
            }
            transfeeMapper.delete(new LambdaQueryWrapper<Transfee>()
                    .eq(Transfee::getTransportId,id));
        }
    }

    /**
     * 修改运费模板
     */
    @Override
    @Transactional
    public boolean updateById(Transport entity) {
        Assert.notNull(entity, "要修改的数据不能为Null");
        Assert.notNull(entity.getTransportId(),"要修改的ID不能为Null");
       // removeByIds(Arrays.asList(entity.getTransportId()));
        //删除附属的表
        boolean falg = super.updateById(entity);
        deleteRealtion(entity.getTransportId());
        //新增附属表
        saveFeeTransport(entity);
        return falg;
    }

    /**
     * 计算运费
     */

    @Override
    public BigDecimal calFee(Long addrId, List<ShopCartItem> shopCartItems, BigDecimal totalPay) {

        return new BigDecimal("10.00");
    }
}
